package lt.marsrutai.mobile.android.fragment;

import java.util.Calendar;
import java.util.Date;

import lt.marsrutai.mobile.android.activity.intent.FastestRoutesSearchIntentHolder;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class DatePickerFragment extends DialogFragment {

    private OnDateSetListener callback;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        FastestRoutesSearchIntentHolder intentHolder = new FastestRoutesSearchIntentHolder(getArguments());

        // Use previously selected date as the default date in the picker
        Date selectedDate = new Date(intentHolder.getCurrentlySelectedDate());
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(selectedDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), callback, year, month, day);
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            // Register parent activity as a callback listener
            callback = (OnDateSetListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement " + OnDateSetListener.class);
        }
    }
}
